package com.atguigu.tingshu.album.service;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2024-11-01 09:34
 */
@Slf4j
@Service
public class TestService {

    @Autowired
    private RedissonClient redissonClient;

    public void read(Long id) {
        //1.创建读写锁对象 锁名称前缀:数据标识
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("myLock:" + id);
        RLock lock = readWriteLock.readLock();

        //2.获取读锁成功 执行读操作  读锁持有期间，不允许并发发写，允许并发读
        try {
            lock.lock(5, TimeUnit.SECONDS);
            log.info(Thread.currentThread().getName() + "执行读数据操作");
        } finally {
            //3.释放读锁
            //lock.unlock();
        }
    }

    public void write(Long id) {
        //1.创建读写锁对象 锁名称前缀:数据标识
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("myLock:" + id);
        //2.获取写锁成功 执行写操作  写锁持有期间，不允许并发读，并发写
        RLock lock = readWriteLock.writeLock();
        lock.lock(5, TimeUnit.SECONDS);
        try {
            log.info(Thread.currentThread().getName() + "执行写入操作");
        } finally {
            //3.释放写锁
            //lock.unlock();
        }
    }
}
